package cn.com.lyb.flink.window;

import cn.com.lyb.flink.bean.WaterSensor;
import cn.com.lyb.flink.split.WaterSensorMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.GlobalWindows;
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

public class WindowApiDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> sensorDS = env.socketTextStream("172.32.1.6", 1234).map(new WaterSensorMapFunction());

        KeyedStream<WaterSensor, String> keyBy = sensorDS.keyBy((KeySelector<WaterSensor, String>) waterSensor -> waterSensor.getId());
        // 指定窗口分配器，指定 用 哪一种窗口  时间OR计数？ 滚动 滑动 会话
        // 没有keyBy的窗口 windowAll  窗口内的所有数据进入同一个子任务，并行度只能为1
        //sensorDS.windowAll().
        // 有keyBy的窗口 每个key都定义了一组窗口，各自独立的进行统计计算



        // 基于时间的窗口
        // keyBy.window(TumblingProcessingTimeWindows.of(Time.seconds(10))); // 滚动窗口，窗口长度为10s
        //keyBy.window(SlidingProcessingTimeWindows.of(Time.seconds(10), Time.seconds(2))); // 滑动窗口，窗口长度10s，滑动步长2s
        //keyBy.window(ProcessingTimeSessionWindows.withGap(Time.seconds(5))); // 会话窗口， 超时间隔5s

        // 基于计数的
        // keyBy.countWindow(5); // 滚动窗口，窗口长度=5个元素
        keyBy.countWindow(5, 10); // 滑动窗口，窗口长度为5个元素，滑动步长=2个元素
        //keyBy.window(GlobalWindows.create());//  全局窗口，计数窗口底层就是用这个,需要自己定义触发器，很少用

        // 指定窗口函数 窗口内数据的计算逻辑
        WindowedStream<WaterSensor, String, TimeWindow> window = keyBy.window(TumblingProcessingTimeWindows.of(Time.seconds(10)));
        // 增量聚合函数：来一条数据，计算一条数据； 窗口触发的时候输出计算结果
       // window
               // .reduce()
                     //  .aggregate();
        // 全窗口函数：数据来了不计算，存起来，窗口触发的时候，计算并输出结果
        //window.process();


        env.execute();
    }
}
